package com.bysc.userservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.userservice.entity.UserInfoTitle;
import com.bysc.userservice.entity.UserTitle;
import com.bysc.userservice.entity.UserUseTitle;
import com.bysc.userservice.entity.vo.TitleListVo;
import com.bysc.commonutils.vo.TitleVo;
import com.bysc.userservice.service.UserInfoTitleService;
import com.bysc.userservice.service.UserTitleService;
import com.bysc.userservice.service.UserUseTitleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2024-05-20
 */
@Api(tags = "头衔管理")
@RestController
@RequestMapping("/userservice/user-title")
public class UserTitleController {
    @Autowired
    private UserTitleService userTitleService;

    @Autowired
    private UserInfoTitleService userInfoTitleService;
    @Autowired
    private UserUseTitleService userUseTitleService;

    @ApiOperation(value = "新增头衔")
    @PostMapping("addTitle")
    public Results addTitleByTitleId(@ApiParam(name = "TitleInfo", value = "头衔信息", required = true) @RequestBody UserTitle userTitle) {
        try {
            userTitleService.save(userTitle);
            return Results.ok().message(MessageConstant.ADD_TITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_TITLE_FAIL);
        }
    }

    @ApiOperation(value = "根据头衔id删除头衔")
    @DeleteMapping("deleteTitleById/{id}")
    public Results deleteTitleById(@ApiParam(name = "id", value = "头衔id", required = true) @PathVariable String id) {
        try {

            UserTitle title = userTitleService.getById(id);
            if (title != null) {
                if (title.getIsPrivate()) {
                    userInfoTitleService.remove(new QueryWrapper<UserInfoTitle>().eq("title_id", title.getId()));
                }
                userTitleService.removeById(id);
                userUseTitleService.remove(new QueryWrapper<UserUseTitle>().eq("title_id", title.getId()));
            }
            return Results.ok().message(MessageConstant.DELETE_TITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_TITLE_FAIL);
        }
    }

    @ApiOperation(value = "根据头衔id修改头衔信息")
    @PutMapping("updateTitleById")
    public Results updateTitleById(@ApiParam(name = "titleInfo", value = "头衔信息", required = true) @RequestBody UserTitle userTitle) {
        try {
            userTitleService.updateById(userTitle);
            return Results.ok().message(MessageConstant.EDIT_TITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_TITLE_FAIL);
        }
    }

    @ApiOperation(value = "根据头衔id修改公开")
    @PutMapping("updatePublicTitelById/{id}")
    public Results updatePublicTitelById(@ApiParam(name = "id", value = "头衔id", required = true)
                                         @PathVariable String id) {
        try {
            UserTitle title = userTitleService.getById(id);
            if (title != null) {
                Boolean isDisable = title.getIsPrivate();
                isDisable = !isDisable;
                title.setIsPrivate(isDisable);
                userTitleService.updateById(title);
            }
            return Results.ok().message(MessageConstant.EDIT_TITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_TITLE_FAIL);
        }
    }

    @ApiOperation(value = "根据用户id查找用户使用的头衔信息")
    @GetMapping("getTitleByUserId/{id}")
    public Results getTitleById(@ApiParam(name = "id", value = "用户id", required = true) @PathVariable String id) {
        try {
            List<UserUseTitle> titles = userUseTitleService.list(new QueryWrapper<UserUseTitle>().eq("user_id", id));
            ArrayList<TitleVo> res = new ArrayList<>();
            for (UserUseTitle title : titles) {
                String titleId = title.getTitleId();
                UserTitle userTitle = userTitleService.getById(titleId);
                TitleVo titleVo = new TitleVo();
                BeanUtils.copyProperties(userTitle, titleVo);
                res.add(titleVo);
            }
            return Results.ok().data("titles", res).message(MessageConstant.QUERY_USETITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_USETITLE_FAIL);
        }
    }

    @ApiOperation(value = "根据用户id查找用户拥有头衔列表")
    @GetMapping("getTitleListByToken")
    public Results getTitleListByToken(HttpServletRequest request) {
        try {
            String userId = JwtUtils.getMemberIdByJwtToken(request);

            HashMap<String, List> map = userTitleService.getTitleListById(userId);

            return Results.ok().data("map", map).message(MessageConstant.QUERY_INFOTITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_INFOTITLE_FAIL);
        }
    }

    @ApiOperation(value = "用户选择并保存头衔")
    @PostMapping("updateTitleByToken")
    public Results saveTitleByToken(@RequestBody TitleListVo titleListVo, HttpServletRequest request) {
        try {
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            ArrayList<UserUseTitle> titles = new ArrayList<>();
            for (String titleId : titleListVo.getTitleIdList()) {
                UserUseTitle useTitle = new UserUseTitle();
                useTitle.setUserId(userId);
                useTitle.setTitleId(titleId);
                titles.add(useTitle);
            }
            userUseTitleService.remove(new QueryWrapper<UserUseTitle>().eq("user_id", userId));
            userUseTitleService.saveBatch(titles);
            return Results.ok().message(MessageConstant.EDIT_USETITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_USETITLE_FAIL);
        }
    }

    @ApiOperation(value = "可带条件分页查询头衔")
    @PostMapping("getTitle/{page}/{limit}")
    public Results getTitle(@PathVariable Long page,
                            @PathVariable Long limit,
                            @RequestBody TitleVo titleVo) {
        try {
            Page<UserTitle> pageParam = new Page<>(page, limit);
            LambdaQueryWrapper<UserTitle> wrapper = new LambdaQueryWrapper<>();
            String title = titleVo.getTitle();
            String id = titleVo.getId();
            Boolean isPrivate = titleVo.getIsPrivate();
            if (!StringUtils.isEmpty(id)) {
                wrapper.eq(UserTitle::getId, id);
            }
            if (isPrivate != null) {
                wrapper.eq(UserTitle::getIsPrivate, isPrivate);
            }
            if (!StringUtils.isEmpty(title)) {
                wrapper.like(UserTitle::getTitle, title);
            }
            IPage<UserTitle> iPage = userTitleService.page(pageParam, wrapper);
            return Results.ok().data("list", iPage).message(MessageConstant.QUERY_TITLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_TITLE_FAIL);
        }

    }

}

